<?php


namespace App\Models\Traits;


use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Redis;

trait LastActivedAtHelper
{
    // 缓存相关
    protected $hash_prefix = "larabbs_last_actived_at";
    protected $field_prefix = 'user_';

    public function recordLastActivedAt()
    {
        // Redis 的哈希表的命名，如：larabbs_last_actived_at_2022-11-11
        $hash = $this->getHashFromDataString(Carbon::now()->toDateString());

        // 字段的名称，如 user_1
        $field = $this->getHashField();

        // 当前时间，如： 2022-11-09 23:43:22
        $now = Carbon::now()->toDateTimeString();

        // 数据写入 Redis，字段已存在会被更新
        Redis::hset($hash, $field, $now);
    }

    public function syncUserActiveAt()
    {
        // 获取昨天的日期

        $hash = $this->getHashFromDataString(Carbon::yesterday()->toDateString());
        $datas = Redis::hGetAll($hash);

        // 遍历，并同步到数据库中
        foreach ($datas as $user_id => $actived_at) {
            // 会将 user_1 转为 1
            $user_id = str_replace($this->field_prefix, '', $user_id);
            $user    = $this->find($user_id);
            if ($user) {
                $user->last_actived_at = $actived_at;
                $user->save();
            }
        }

        // 以数据库为中心的存储，既已同步，即可删除
        Redis::del($hash);
    }

    public function getLastActivedAtAttribute($value)
    {
        $hash = $this->getHashFromDataString(Carbon::now()->toDateString());

        // 字段的名称，如 user_1
        $field = $this->getHashField();

        $datetime = Redis::hGet($hash, $field) ?: $value;

        // 如果存在的话，返回对应的 Carbon 实体
        if ($datetime) {
            return new Carbon($datetime);
        } else {
            return $this->created_at;
        }
    }

    public function getHashFromDataString($date)
    {
        // Redis 的哈希表的命名，如：larabbs_last_actived_at_2022-11-11
       return $this->hash_prefix . $date;
    }

    public function getHashField()
    {
        // 字段名称，如：user_1
        return $this->field_prefix . $this->id;
    }
}
